<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<link rel="stylesheet" type="text/css"
	href="<%=request.getContextPath()%>/js/css/style.css" />
<script type="text/javascript" src="<%=request.getContextPath()%>/js/validation1.js"></script>	
<style>
 #div_search,#div_search>*{
 	vertical-align: middle;
 }
</style>
 <table id="res_box" align= "center"></table>

<div id="res_tb" style="padding:5px;">
	<div style="margin-bottom:5px;">
		<a href="#" class="easyui-linkbutton" iconCls="icon-add" plain="true" onclick="obj2.add();">添加</a>
		<a href="#" class="easyui-linkbutton" iconCls="icon-edit" plain="true" onclick="obj2.edit();">修改</a>
		<a href="#" class="easyui-linkbutton" iconCls="icon-remove" plain="true" onclick="obj2.remove();">删除</a>
		<a href="#" class="easyui-linkbutton" iconCls="icon-save" plain="true" style="display:none;" id="res_save" onclick="obj2.save();">保存</a>
		<a href="#" class="easyui-linkbutton" iconCls="icon-redo" plain="true" style="display:none;" id="res_redo" onclick="obj2.redo();">取消编辑</a>		
	</div>
	<div id="res_search" style="padding:0 0 0 7px;color:#333;">
		查询资源：<input type="text" class="textbox" name="ResourceName" style="width:110px">
		创建时间从：<input type="text" name="res_date_from" class="easyui-datebox" editable="false" style="width:110px">
		到：<input type="text" name="res_date_to" class="easyui-datebox" editable="false" style="width:110px">
		<a href="#" class="easyui-linkbutton " iconCls="icon-search" style="vertical-align: middle;" onclick="obj2.search();">查询</a>
	</div>
</div>
   
   <div id="dg"></div>
   
   <div class="form_content">
  <form id="res_add" action="./resource/upload" enctype="multipart/form-data" method="post" >
    <fieldset>
        <legend>资源信息</legend>
        <div class="form-row">
            <div class="field-label">资源名称</div>
            <div class="field-widget"><input name="ResourceName" id="ResourceName" class="required" title="Enter your ResourceName" /></div><div class="validation-advice" id="advice-required-ResourceName" style="display: none;">不能为空</div>
        </div>
        <div class="form-row">
            <div class="field-label"><label for="field6">资源类别</label>:</div>
            <div class="field-widget">
                <select id="ResourceType" name="ResourceType" class="validate-selection" title="Choose your ResourceTpye">
                    <option value="">请选择</option>
                    <option value="W">windows软件</option>
                    <option value="U">Ubuntu软件</option>
                    <option value="D">安装文档</option>
                    <option value="O">其他软件</option>
                    
                </select>
                <div class="validation-advice" id="advice-validate-selection-ResourceTpye" style="display: none;width: 60px;">请选择类别</div>
            </div>
        </div>
        <div class="form-row">
            <div class="field-label"><label for="field2">资源路径</label>:<input type="radio" class="radio_input" name="UrlType" id="Resource_url" value="1"  checked="checked" onclick="to_change()"/>输入地址</div>
            <div class="field-widget"><input name="ResourceUrl"  id="ResourceUrl" class="required" title="Enter your ResourceUrl" /></div><div class="validation-advice" id="advice-required-ResourceUrl" style="display: none;">不能为空</div>
        </div>
        <div class="form-row">
            <div class="field-label">
              <label for="field2">&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp;</label><input type="radio" class="radio_input" name="UrlType" id="Resource_file" value="2" onclick="to_change()" />上传文件</div><input type="file" id="resfile" name="resfile" disabled="disabled" class="submit" style="background-color: #F3FCFE;color: #0B0A0A;"/>
            <div class="field-widget">

     </div>
        </div>
        
        <div class="form-row">
            <div class="field-label"><label for="field3">资源描述</label>:</div>
            <div class="field-widget"><textarea name="ResourceDes" style="border: 1px solid #0C0;
color: #000;width: 510px;
height: 156px;
float: left;background-color: #F3FCFE;"></textarea></div>
        </div>
        
        
    </fieldset>
    <input type="submit" class="submit" value="提交" onclick="formcheck()"/> <input class="reset" type="button" value="重置" onclick="resetform()" />
    </form>
    </div>


 <script type="text/javascript">
 
$(function () {  
	obj2 = {
		/* editRow : undefined, */
		search : function () {
			$('#res_box').datagrid('load', {
				ResourceName : $.trim($('input[name="ResourceName"]').val()),
				date_from : $('input[name="res_date_from"]').val(),
				date_to : $('input[name="res_date_to"]').val(),
				
			});
		},
		add : function () {
			$('#res_add').dialog('open');
			/* $('input[name="name"]').focus(); */
		},
		/* edit : function () {
			var rows = $('#box2').datagrid('getSelections');
			if (rows.length > 1) {
				$.messager.alert('警告操作！', '编辑记录只能选定一条数据！', 'warning');
			} else if (rows.length == 1) {
				$.ajax({
					url : 'adress/findadress',
					type : 'post',
					data : {
						id : rows[0].id,
					},
					beforeSend : function () {
						$.messager.progress({
							text : '正在获取中...',
						});
					},
					success : function (data, response, status) {
						$.messager.progress('close');
						
						if (data) {
							$('#adress_edit').form('load', {
								id : data.id,
								company : data.company,
								phone : data.phone,
								adress : data.adress,
								servicephone : data.servicephone,
								fax : data.fax,
								zipcode : data.zipcode,
								//auth_edit : obj[0].auth,
							}).dialog('open');
							
							
							
						} else {
							$.messager.alert('获取失败！', '未知错误导致失败，请重试！', 'warning');
						}
					}
				});
			} else if (rows.length == 0) {
				$.messager.alert('警告操作！', '编辑记录至少选定一条数据！', 'warning');
			} 
		},*/
		remove : function () {
			var rows = $('#res_box').datagrid('getSelections');
			if (rows.length > 0) {
				$.messager.confirm('确定操作', '您正在要删除所选的记录吗？', function (flag) {
					if (flag) {
						var ids = [];
						for (var i = 0; i < rows.length; i ++) {
							ids.push(rows[i].id);
						}
						//console.log(ids.join(','));
						$.ajax({
							type : 'POST',
							url : 'resource/delete',
							data : {
								ids : ids.join(','),
							},
							beforeSend : function () {
								$('#res_box').datagrid('loading');
							},
							success : function (data) {
								if (data) {
									$('#res_box').datagrid('loaded');
									$('#res_box').datagrid('load');
									$('#res_box').datagrid('unselectAll');
									$.messager.show({
										title : '提示',
										msg : data + '个资源被删除成功！',
									});
								}
							},
						});
					}
				});
			} else {
				$.messager.alert('提示', '请选择要删除的记录！', 'info');
			}
		}, 
	};
		
	 $('#res_add').dialog({
		width : 650,
		title : '新增管理',
		modal : true,
		closed : true,
		/* buttons : [{
			text : '提交',
			handler : function () {
				if ($('#adress_add').form('validate')) {
				    var sharingresource = $("#add_resource").serialize();
					$.ajax({
						url : 'resource/resource_update',
						type : 'post',
						data : sharingresource,
						beforeSend : function () {
							$.messager.progress({
								text : '正在新增中...',
							});
						},
						success : function (data, response, status) {
							$.messager.progress('close');
							
							if (data == "success") {
								$.messager.show({
									title : '提示',
									msg : '新增成功',
								});
								$('#adress_add').dialog('close').form('reset');
								$('#box2').datagrid('reload');
							} else {
								$.messager.alert('新增失败！', '未知错误导致失败，请重试！', 'warning');
							}
						}
					});
				}
			},
		},{
			text : '取消',
			iconCls : 'icon-redo',
			handler : function () {
				$('#adress_add').dialog('close').form('reset');
			},
		}], */
	}); 


  $('#res_box').datagrid({
        fit : true,
		//width : 800,
		//url : 'content.json',
		url : 'resource_datagrid',
		title : '资源列表',
		iconCls : 'icon-search',
		striped : true,
		nowrap : true,
		rownumbers : true,
		//singleSelect : true,
		fitColumns : true,
		columns : [[
			{
				field : 'id',
				title : '编号',
				sortable : true,
				width : 100,
				checkbox : true,
			},
			{
				field : 'resourceName',
				title : '资源名称',
				sortable : true,
				width : 100,
				editor : {
					type : 'validatebox',
					options : {
						required : true,
					},
				},
			},
			{
				field : 'resourceUrl',
				title : '资源链接',
				sortable : true,
				width : 100,
				editor : {
					type : 'validatebox',
					options : {
						required : true,
					},
				},
			},
			{
				field : 'resourceType',
				title : '资源类别',
				sortable : false,
				width : 100,
				editor : {
					type : 'combobox',
					options : {
					          data :  [{"value1":"W" ,"show1" :"windows" },{"value1":"U","show1" :"Ununtu" },{"value1":"D","show1" :"说明文档" },{"value1":"O","show1" :"其他软件" }] ,
					          valueField: 'value1',    
                              textField: 'show1', 
                              editable: false, //不允许手动输入 
                              panelHeight: 'auto' ,
                             
                              },
					},
				formatter : function(value ,rowData ,rowIndex){
				    if(value == "W"){
				      return "windows" ;
				    }else if(value == "U"){
				      return "Ununtu" ;
				    }else if(value == "D"){
				      return "说明文档" ;
				    }else{
				      return "其他软件" ;
				    }
				}
			},			
			{
				field : 'creatDate',
				title : '创建时间',
				sortable : true,
				width : 100,
				/* editor : {
					type : 'datetimebox',
					options : {
						required : true,
						editable: true, //不允许手动输入 
					},
				}, */
				formatter :  formatDateBoxFull,
			},
			{
				field : 'downloadCount',
				title : '下载次数',
				sortable : true,
				width : 100,
				/* editor : {
					type : 'validatebox',
					}, */
			},
		]],
		toolbar : '#res_tb',
		border : false,
		pagination : true,
		pageSize : 23,
		pageList : [10, 23, 30],
		pageNumber : 1,
		sortName : 'id',
		sortOrder : 'DESC',
		
		 //双击编辑
		/* onDblClickRow : function (rowIndex, rowData) {
		
			if (obj2.editRow != undefined) {
				$('#res_box').datagrid('endEdit', obj2.editRow);
			}
		
			if (obj2.editRow == undefined) {
				$('#res_save,#res_redo').show();
				$('#res_box').datagrid('beginEdit', rowIndex);
				obj2.editRow = rowIndex;
			}
			
		}, */
		/* onAfterEdit : function (rowIndex, rowData, changes) {
			$('#res_save,#res_redo').hide();
			
			var inserted = $('#res_box').datagrid('getChanges', 'inserted');
			var updated = $('#res_box').datagrid('getChanges', 'updated');
			
			var url = info =  '';
			
			//新增资源
			if (inserted.length > 0) {
				url = 'user/user_update';
				info = '新增';
			}
			
			//修改资源
			if (updated.length > 0) {
				url = 'user/user_update';
				info = '修改';
			}
			
			$.ajax({
				type : 'POST',
				url : url,
				data : {
					id : rowData["id"],
					username : rowData["username"],
					creatTime1 : rowData["creatTime"],
					role : rowData["role"],
					isForbidden : rowData["isForbidden"],
				},
				beforeSend : function () {
					$('#res_box').datagrid('loading');
				},
				success : function (data) {
					if (data == "success") {
						$('#res_box').datagrid('loaded');
						$('#res_box').datagrid('load');
						$('#res_box').datagrid('unselectAll');
						$.messager.show({
							title : '提示',
							msg : '资源' + info + '成功！',
						});
						obj2.editRow = undefined;
					}else{
					    $('#res_box').datagrid('loaded');
						$('#res_box').datagrid('load');
						$('#res_box').datagrid('unselectAll');
						$.messager.show({
							title : '提示',
							msg : '资源名重复，'+ info + '失败',
						});
						obj2.editRow = undefined;
					}
				},
			});
			//console.log(rowData);
		}, */
	});
	
});
  


       
/*该方法使日期列的显示符合阅读习惯*/
//datagrid中用法：{ field:'StartDate',title:'开始日期', formatter: formatDatebox, width:80}
function formatDatebox(value) {
    if (value == null || value == '') {
        return '';
    }
    var dt = parseToDate(value);
    return dt.format("yyyy-MM-dd"); 
}

/*转换日期字符串为带时间的格式*/
function formatDateBoxFull(value) {
    if (value == null || value == '') {
        return '';
    }
    var dt = parseToDate(value);
    return dt.format("yyyy-MM-dd ");
}

//辅助方法(转换日期)
function parseToDate(value) {
    if (value == null || value == '') {
        return undefined; 
    }

    var dt;
    if (value instanceof Date) {
        dt = value;
    }
    else {
        if (!isNaN(value)) {
            dt = new Date(value);
        }
        else if (value.indexOf('/Date') > -1) {
            value = value.replace(/\/Date\((-?\d+)\)\//, '$1');
            dt = new Date();
            dt.setTime(value);
        } else if (value.indexOf('/') > -1) {
            dt = new Date(Date.parse(value.replace(/-/g, '/')));
        } else {
            dt = new Date(value);
        }
    }
    return dt;
}

//为Date类型拓展一个format方法，用于格式化日期
Date.prototype.format = function (format) //author: meizz 
{
    var o = {
        "M+": this.getMonth() + 1, //month 
        "d+": this.getDate(),    //day 
        "h+": this.getHours(),   //hour 
        "m+": this.getMinutes(), //minute 
        "s+": this.getSeconds(), //second 
        "q+": Math.floor((this.getMonth() + 3) / 3),  //quarter 
        "S": this.getMilliseconds() //millisecond 
    };
    if (/(y+)/.test(format))
        format = format.replace(RegExp.$1,
                (this.getFullYear() + "").substr(4 - RegExp.$1.length));
    for (var k in o)
        if (new RegExp("(" + k + ")").test(format))
            format = format.replace(RegExp.$1,
                    RegExp.$1.length == 1 ? o[k] :
                        ("00" + o[k]).substr(("" + o[k]).length));
    return format;
};
 
//以下拓展是为了datagrid的日期列在编辑状态下显示正确日期
$.extend(
    $.fn.datagrid.defaults.editors, {
        datebox: {
            init: function (container, options) {
                var input = $('<input type="text">').appendTo(container);
                input.datebox(options);
                return input;
            },
            destroy: function (target) {
                $(target).datebox('destroy');
            },
            getValue: function (target) {
                return $(target).datebox('getValue');
            },
            setValue: function (target, value) {
                $(target).datebox('setValue', formatDatebox(value));
            },
            resize: function (target, width) {
                $(target).datebox('resize', width);
            }
        },
        datetimebox:{
            init: function (container, options) {
                var input = $('<input type="text">').appendTo(container);
                input.datetimebox(options);
                return input;
            },
            destroy: function (target) {
                $(target).datetimebox('destroy');
            },
            getValue: function (target) {
                return $(target).datetimebox('getValue');
            },
            setValue: function (target, value) {
                $(target).datetimebox('setValue', formatDateBoxFull(value));
            },
            resize: function (target, width) {
                $(target).datetimebox('resize', width);
            }
        }
    });

    
    </script>

